package at.htlkaindorf.jsf.view;

import java.io.IOException;
import java.io.Serializable;
import java.util.Date;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import at.htlkaindorf.jsf.application.DataBean;
import at.htlkaindorf.jsf.domain.Entry;
import at.htlkaindorf.jsf.session.SessionBean;

@ManagedBean(name = "actionsBean")
@ViewScoped
public class ActionsBean implements Serializable {

    private static final long serialVersionUID = -5465713085337374234L;

    private final Logger logger = LoggerFactory.getLogger(ActionsBean.class);

    @ManagedProperty(value = "#{dataBean}")
    private DataBean dataBean;

    @ManagedProperty(value = "#{sessionBean}")
    private SessionBean sessionBean;

    private Entry entry;

    @PostConstruct
    public void init() {
        if (sessionBean.getUsername() == null) {
            try {
                FacesContext.getCurrentInstance().getExternalContext().redirect("guestbookLogin.xhtml");
            } catch (IOException e) {
                logger.error(null, e);
            }
        }
    }

    public ActionsBean() {
        entry = new Entry();
    }

    public String createEntry() {
        String username = sessionBean.getUsername();
        dataBean.addNewEntry(username, entry.getEmail(), entry.getTitle(), entry.getText());
        return "guestbookOverview.xhtml";
    }

    public String deleteEntry() {
        dataBean.deleteEntry(entry);
        return "guestbookOverview.xhtml";
    }

    public String updateEntry() {
        entry.setPostDate(new Date());
        // Entry object is already data object and is updated automatically by JSF
        return "guestbookOverview.xhtml";
    }

    // invoked by event of metadata of type 'preRenderView'
    public void loadEntryToUpdate(ComponentSystemEvent event) {
        Entry entryToUpdate = dataBean.getEntryById(entry.getId());
        entry = entryToUpdate;
    }

    public Entry getEntry() {
        return entry;
    }

    public void setEntry(Entry entry) {
        this.entry = entry;
    }

    public DataBean getDataBean() {
        return dataBean;
    }

    public void setDataBean(DataBean dataBean) {
        this.dataBean = dataBean;
    }

    public SessionBean getSessionBean() {
        return sessionBean;
    }

    public void setSessionBean(SessionBean sessionBean) {
        this.sessionBean = sessionBean;
    }
}
